<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * This page return the result of the request of users, if no query returns all users.
 *
 * @package   block_email_list
 * @author    Toni Mas <toni.mas@uib.dot.es>
 * @copyright 2006 by <toni.mas at uib dot es>
 * @license   http://www.affero.org/oagpl.html  AFFERO GENERAL PUBLIC LICENSE
 * @uses $CFG
 * @uses $DB;
 * @uses $PAGE;
 */
require_once(dirname(__FILE__).'/../../../config.php');
require_once($CFG->dirroot.'/blocks/email_list/email/tablelib.php');
require_once($CFG->dirroot.'/blocks/email_list/email/lib.php');
require_once($CFG->dirroot.'/blocks/email_list/email/list.class.php');
require_once($CFG->libdir.'/searchlib.php');
require_once($CFG->libdir.'/grouplib.php');

$courseid = optional_param('id', SITEID, PARAM_INT);   // Course ID
$currentgroup = optional_param('group', 0, PARAM_INT); // Selected Group
$roleid = optional_param('roleid', 0, PARAM_INT);      // Role ID
$page = optional_param('page', 0, PARAM_INT);          // Page
$perpage = optional_param('perpage', 7, PARAM_INT);    // Max rows per page
$search = optional_param('search', '', PARAM_RAW);     // Searching users

$sort = ''; // BJB20101014: fix undefined var $sort

$firstinitial = optional_param('fname', '', PARAM_ALPHA);   // Order by fistname
$lastinitial = optional_param('lname', '', PARAM_ALPHA);    // Order by lastname
$showlists = optional_param('showlists', 0, PARAM_INT);
if (empty($showlists)) {
    $showhidelists = 0;
}

global $CFG, $USER; // req'd by lists

// Get course, if exist
if (! $course = $DB->get_record('course', array('id' => $courseid))) {
    print_error('invalidcourseid', 'block_email_list');
}

// Only return, if user have login
require_login($course);

// Need capability viewaparticipants.
require_capability('moodle/course:viewparticipants', $PAGE->context);


$tablecolumns = array( 'user', 'to', 'cc', 'bcc', 'dropall' );

$urlto     = '<a href="#" onclick="action_all_users(\'to\');" > '.get_string('toall', 'block_email_list')
           .' <img src="'.$CFG->wwwroot.'/blocks/email_list/email/images/user_green.png"'
           .' height="16" width="16" alt="'.get_string('course').'" /> </a>';
$urlcc     = '<a href="#" onclick="action_all_users(\'cc\');" >'.get_string('ccall', 'block_email_list')
           .' <img src="'.$CFG->wwwroot.'/blocks/email_list/email/images/user_gray.png"'
           .' height="16" width="16" alt="'.get_string('course').'" /> </a>';
$urlbcc    = '<a href="#" onclick="action_all_users(\'bcc\');" >'.get_string('bccall', 'block_email_list')
           .' <img src="'.$CFG->wwwroot.'/blocks/email_list/email/images/user_suit.png"'
           .' height="16" width="16" alt="'.get_string('course').'" /> </a>';
$urlremove = '<a href="#" onclick="action_all_users(\'remove\');" >'.get_string('removeall', 'block_email_list')
           .' <img src="'.$CFG->wwwroot.'/blocks/email_list/email/images/user_red.png"'
           .' height="16" width="16" alt="'.get_string('course').'" /> </a>';

$tableheaders = array( get_string('user'), $urlto, $urlcc, $urlbcc, $urlremove );
$baseurl = 'participants.php?id='.$course->id.'&amp;roleid='.$roleid.'&amp;group='.$currentgroup.
           '&amp;perpage='.$perpage.'&amp;search='.$search.'&amp;fname='.$firstinitial.
           '&amp;lname='.$lastinitial.'&amp;showlists='.$showlists;

$table = new email_flexible_table('participants');

$table->define_columns($tablecolumns);
$table->define_headers($tableheaders);
$table->define_baseurl($baseurl);

$table->set_attribute('align', 'center');

$table->setup();

$sitecontext = context_system::instance();
$frontpagectx = context_course::instance(SITEID);

/// front page course is different
$rolenames = array();

list($roles, $avoidroles) = get_mailable_roles($PAGE->context);

foreach ($roles as $role) {
    $rolenames[$role->id] = strip_tags(role_get_name($role, $PAGE->context));   // Used in menus etc later on
}

if (($PAGE->context->id == $frontpagectx->id) && $CFG->defaultfrontpageroleid) {
    // default frontpage role is assigned to all site users
    unset($rolenames[$CFG->defaultfrontpageroleid]);
}

// no roles to display yet?
// frontpage course is an exception, on the front page course we should display all users
if (empty($rolenames) && ($PAGE->context->id != $frontpagectx->id)) {
    print_error('No participants found for this course');
}

/// Check to see if groups are being used in this course
/// and if so, set $currentgroup to reflect the current group

$groupmode    = groups_get_course_groupmode($course);   // Groups are being used
$currentgroup = groups_get_course_group($course, true);

if (!$currentgroup) {      // To make some other functions work better later
    $currentgroup  = null;
}

$isseparategroups = ($course->groupmode == SEPARATEGROUPS and $course->groupmodeforce and
!has_capability('moodle/site:accessallgroups', $PAGE->context));


$values = array();

// we are looking for all users with this role assigned in this context or higher
if ($usercontexts = get_parent_contexts($PAGE->context)) {
    $listofcontexts = '('.implode(',', $usercontexts).')';
} else {
    $listofcontexts = '('.$sitecontext->id.')'; // must be site
}

$fields = explode(',', user_picture::fields('u', array('username')));
$fields[] = 'ctx.id as ctxid';
$fields[] = 'ctx.path as ctxpath';
$fields[] = 'ctx.depth AS ctxdepth';
$fields[] = 'ctx.contextlevel AS ctxlevel';

$distinct = '';
if ($PAGE->context->id != $frontpagectx->id) {
    $distinct = ' DISTINCT';
}

$from = ' FROM {user} u'
       .' LEFT OUTER JOIN {context} ctx'
         .' ON (u.id=ctx.instanceid AND ctx.contextlevel = '.CONTEXT_USER.') ';

// Not on frontpage and we don't want all registered users
if ($PAGE->context->id != $frontpagectx->id or $roleid >= 0) {
    $from  .= ' JOIN {role_assignments} r'
               .' ON u.id=r.userid'
             .' LEFT OUTER JOIN {user_lastaccess} ul'
               .' ON (r.userid=ul.userid and ul.courseid = ?) ';
    $values[] = $course->id;
}

// join on 2 conditions
// otherwise we run into the problem of having records in ul table, but not relevant course
// and user record is not pulled out
$values[] = 0;
$values[] = 'guest';
$where  = ' WHERE u.deleted=? AND u.username != ?';

if (($PAGE->context->id != $frontpagectx->id) || ($roleid >= 0)) {
    list($clsql, $params) = $DB->get_in_or_equal($listofcontexts);
    $where .= " AND (r.contextid = ? OR r.contextid $clsql)";
    $values[] = $PAGE->context->id;
    $values = array_merge($values, $params);
}

if ($PAGE->context->id != $frontpagectx->id) {
    $where .= ' AND (ul.courseid = ? OR ul.courseid IS NULL)';
    $values[] = $course->id;

    // exclude users with roles we are avoiding
    if (sizeof($avoidroles) > 0) {
        list($arsql, $params) = $DB->get_in_or_equal($avoidroles, SQL_PARAMS_QM, '', false);
        $where .= ' AND r.roleid '. $arsql;
        $values = array_merge($values, $params);
    }
}

if ($roleid > 0) {
    $where .= ' AND r.roleid = ? ';
    $values[] = $roleid;
}

// Searching users
$sqlsearch = '';

if ($currentgroup) {    // Displaying a group by choice
    // FIX: TODO: This will not work if $currentgroup == 0, i.e. "those not in a group"
    $from  .= 'LEFT JOIN {groups_members} gm ON u.id = gm.userid ';
    $where .= ' AND gm.groupid = ?';
    $values[] = $currentgroup;
}

// General search
if (! empty($search) ) {
    $where .= ' AND ('. $DB->sql_like('u.firstname', '?', false)
              .' OR '. $DB->sql_like('u.lastname', '?', false) .')';
    $values[] = '%'. $search .'%';
    $values[] = '%'. $search .'%';
}

// Initial firtname search
if ($firstinitial) {
    $where .= ' AND ('. $DB->sql_like('firstname', '?', false) .')';
    $values[] = $firstinitial .'%';
}

// Initial lastname search
if ($lastinitial) {
    $where .= ' AND ('. $DB->sql_like('lastname', '?', false) .')';
    $values[] = $lastinitial .'%';
}

// Each user could have > 1
$totalcount = $DB->count_records_sql('SELECT COUNT(distinct u.id) '.$from.$where, $values);

// Define long page.
$table->pagesize($perpage, $totalcount);

if ($courseid) {
    $userlist = $DB->get_records_sql('SELECT'. $distinct .' '. implode(', ', $fields) .$from.$where.$sort,
                                     $values, $table->get_page_start(), $table->get_page_size());

    if ($userlist) {

        foreach ($userlist as $user) {
            $pic = $OUTPUT->user_picture($user, array('courseid' => $courseid, 'size' => 30, 'link' => false));

            $query = $_SERVER['QUERY_STRING'];

            $link = 'compose.php?' . $query;
            $link = '#';

            $canseefullname = has_capability('moodle/site:viewfullnames', $PAGE->context);

            $fullname = email_fullname($user, $canseefullname);
            $table->add_data(array(
                    '<a href="#" onClick="if( manageContact(\''.$fullname.'\', \''.$user->id
                      . '\', \'add\', \'to\')){toggleRemoveAction(\''.$user->id.'\');}">'.$pic
                      .'<span>'.$fullname.'</span></a>',
                    '<div id="addto'.$user->id.'" align="center"><input id="'.$fullname
                      .'" name="useridto" type="hidden" value="'.$user->id
                      .'"><input id="addto" type="button" value="'
                      .get_string('for', 'block_email_list').'" onClick="if( manageContact(\''
                      .addslashes($fullname).'\', \''.$user->id
                      .'\', \'add\', \'to\')){toggleRemoveAction(\''.$user->id.'\');}"></div>',
                    '<div id="addcc'.$user->id.'" align="center"><input id="'.$fullname
                      .'" name="useridcc" type="hidden" value="'.$user->id
                      .'"><input id="addcc" type="button" value="'
                      .get_string('cc', 'block_email_list').'" onClick="if( manageContact(\''
                      .addslashes($fullname).'\', \''.$user->id
                      .'\', \'add\', \'cc\')){toggleRemoveAction(\''.$user->id.'\');}"></div>',
                    '<div id="addbcc'.$user->id.'" align="center"><input id="'.$fullname
                      .'" name="useridbcc" type="hidden" value="'.$user->id
                      .'"><input id="addbcc" type="button" value="'
                      .get_string('bcc', 'block_email_list').'" onClick="if( manageContact(\''
                      .addslashes($fullname).'\', \''.$user->id.
                      '\', \'add\', \'bcc\')){toggleRemoveAction(\''.$user->id.'\');}"></div>',
                    '<div id="removeuser'.$user->id
                      .'" style="visibility:hidden;align:center"><input id="'.$fullname
                      .'" name="useridremove" type="hidden" value="'.$user->id
                      .'"><a href="#" onClick="if( manageContact(\''.addslashes($fullname)
                      .'\', \''.$user->id.'\', \'remove\', \'\')){toggleRemoveAction(\''.$user->id
                      .'\');}"><img src="'. $OUTPUT->pix_url('t/emailno') .'" alt="'
                      .get_string('remove', 'block_email_list').'" title="'
                      .get_string('remove', 'block_email_list').'"></a></div>'));
        }
    }
}

if ($showlists) {
    $listselect = "owner = {$USER->id} ";
    if ( !empty($firstinitial) ) {
        $listselect .= "AND (listname $like '{$firstinitial}%') ";
    }
    if ( !empty($search) ) {
        $listselect .= "AND (listname $like '%{$search}%') ";
    }
    if ($maillists = $DB->get_records_select('block_email_list_lists', $listselect)) {
        foreach ($maillists as $mlist) {
            $listobj = new maillist();
            $listobj->id       = $mlist->id;
            $listobj->listname = $mlist->listname;
            $listobj->owner    = $mlist->owner;
            if ( $listmembers = $listobj->get_members() ) {
                $uids = -$listobj->id;
                //Above was $uids = ''; but need unique id for browser field
                   //see also: email/lib.php::maillist_to_users()
                foreach ($listmembers as $listentry) {
                    if (!empty($uids)) {
                        $uids .= ',';
                    }
                    $uids .= $listentry->userid;
                }
                $pic = '<img src="'.$CFG->wwwroot.'/pix/i/settings.gif"/>';
                $table->add_data(array(
                        '<a href="#" onClick="if( manageContact(\''.$listobj->listname.'\', \''.$uids.'\', \'add\', \'to\')){toggleRemoveAction(\''.$uids.'\');}">&nbsp;&nbsp;'.$pic.'&nbsp;&nbsp;<span>'.$listobj->listname.'</span></a>',
                        '<div id="addto'.$uids.'" align="center"><input id="'.$listobj->listname.'" name="useridto" type="hidden" value="'.$uids.'"><input id="addto" type="button" value="'.get_string('for','block_email_list').'" onClick="if( manageContact(\''.addslashes($listobj->listname).'\', \''.$uids.'\', \'add\', \'to\')){toggleRemoveAction(\''.$uids.'\');}"></div>',
                        '<div id="addcc'.$uids.'" align="center"><input id="'.$listobj->listname.'" name="useridcc" type="hidden" value="'.$uids.'"><input id="addcc" type="button" value="'.get_string('cc','block_email_list').'" onClick="if( manageContact(\''.addslashes($listobj->listname).'\', \''.$uids.'\', \'add\', \'cc\')){toggleRemoveAction(\''.$uids.'\');}"></div>',
                        '<div id="addbcc'.$uids.'" align="center"><input id="'.$listobj->listname.'" name="useridbcc" type="hidden" value="'.$uids.'"><input id="addbcc" type="button" value="'.get_string('bcc','block_email_list').'" onClick="if( manageContact(\''.addslashes($listobj->listname).'\', \''.$uids.'\', \'add\', \'bcc\')){toggleRemoveAction(\''.$uids.'\');}"></div>',
                        '<div id="removeuser'.$uids.'" style="visibility:hidden;align:center"><input id="'.$listobj->listname.'" name="useridremove" type="hidden" value="'.$uids.'"><a href="#" onClick="if( manageContact(\''.addslashes($listobj->listname).'\', \''.$uids.'\', \'remove\', \'\')){toggleRemoveAction(\''.$uids.'\');}"><img src="'.$OUTPUT->pix_url('/t/emailno').'" alt="'.get_string('remove','block_email_list').'" title="'.get_string('remove','block_email_list').'"></a></div>' )
                );
            }
        }
    }
}

//------------------------- INTERFACE

// Print html
echo '<html>
    <body>';

echo '<script type="text/javascript">';
echo 'parent.changeme("participants","'. $table->get_html(true).'");';
echo 'parent.checkAllRemoveActions();';

echo '</script>';

echo '</body>
    </html>';
